<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['orderReturn:add'])" type="primary"
            @click="handleAddPurchasePlan">新增</el-button>
          <el-button size="mini" v-if="checkPermission(['orderReturn:del'])" type="danger" @click="handleDeletePurchasePlan"
            :disabled="multipleSelection.length === 0">删除</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" placeholder="请输入退货单编号" advanced
            advancedWidth="465">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                <el-form-item label="所属部门">
                  <el-cascader v-model="advancedForm.dept_id" :options="deptList" :props="{
                    label: 'name',
                    value: 'id',
                    emitPath: false,
                    checkStrictly: true
                  }" clearable></el-cascader>
                </el-form-item>
                <el-form-item label="关联订单">
                  <el-input v-model="advancedForm.order_sn" :minlength="2" :maxlength="30" clearable
                    placeholder="请输入关联订单"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="advancedForm.status">
                    <el-option key="NotSubmit" label="未提交" value="NotSubmit" />
                    <el-option key="Submit" label="已提交" value="Submit" />
                    <el-option key="AuditPass" label="审核通过" value="AuditPass" />
                    <el-option key="AuditReject" label="审核驳回" value="AuditReject" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker v-model="advancedForm.purchasePlan_time_range" type="daterange" align="center"
                    :editable="false" unlink-panels :clearable="false" :default-time="['00:00:00', '23:59:59']"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                    :picker-options="{ disabledDate(time) { return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1 }, shortcuts: MixinPickerShortcuts }">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sn" label="退货单编号">
          <template slot-scope="scope">
            <router-link
              v-if="checkPermission(['orderReturn'])"
              style="color: #409eff;"
              :to="{ name: 'orderReturnDetail', params: { id: scope.row.id }, query: { orderType: orderType } }">
              {{ scope.row.sn }}
            </router-link>
            <span v-else>{{scope.row.sn}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="退货日期">
          <template slot-scope="scope">{{ scope.row.return_time | unixToDate }}</template>
        </el-table-column>
        <el-table-column prop="dept_name" label="所属部门" />
        <el-table-column prop="warehouse_name" label="仓库" />
        <el-table-column prop="order_sn" label="关联订单" />
        <el-table-column prop="distribution_name" label="销售经理" />
        <el-table-column prop="handle_by" label="经手人" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">{{ statusFilter(scope.row.status) }}</template>
        </el-table-column>
        <el-table-column prop="audit_by" label="审核人" />
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="success" size="mini" v-if="scope.row.allowable.submit && checkPermission(['orderReturn:submit'])"
              @click="handleSubmitPurchasePlan(scope.row)">提交</el-button>
            <el-button type="danger" size="mini"
              v-else-if="scope.row.allowable.withdraw && checkPermission(['orderReturn:withdraw'])"
              @click="handleWithdrawPurchasePlan(scope.row)">撤回</el-button>
            <el-button type="success" size="mini" v-if="scope.row.allowable.audit && checkPermission(['orderReturn:audit'])"
              @click="handleAuditPurchasePlan(scope.row)">审核</el-button>
            <el-button size="mini" v-if="scope.row.allowable.edit && checkPermission(['orderReturn:edit'])"
              @click="handleEditPurchasePlan(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>
  </div>
</template>

<script>
import * as API_orderReturn from '@/api/orderReturn'
import { Foundation } from '~/ui-utils'
import * as API_Setting from '@/api/setting'
export default {
  name: 'orderReturn',
  data() {
    return {
      deptList: [],
      multipleSelection: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: '',
      orderType: ''
    }
  },
  mounted() {
    this.GET_orderReturnList()
    this.GET_DeptList()
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (newVal.name === 'orderReturn') {
          this.orderType = 'TO_B'
        }
        if (newVal.name === 'retailOrderReturn') {
          this.orderType = 'TO_C'
        }
        this.GET_orderReturnList()
      }
    }
  },
  methods: {
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    statusFilter(val) {
      switch (val) {
        case 'NotSubmit':
          return '未提交'
        case 'Submit':
          return '已提交'
        case 'AuditPass':
          return '审核通过'
        case 'AuditReject ':
          return '审核驳回'
        default:
          return ''
      }
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_orderReturnList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_orderReturnList()
    },
    handleEditPurchasePlan(row) {
      this.$router.push({
        name: 'orderReturnEdit',
        params: { id: row.id },
        query: { orderType: this.orderType }
      })
    },
    /** 添加订单退货 */
    handleAddPurchasePlan() {
      this.$router.push({
        name: 'orderReturnAdd',
        params: { callback: this.GET_orderReturnList },
        query: { orderType: this.orderType }
      })
    },
    handleAuditPurchasePlan(row) {
      this.$router.push({
        name: 'orderReturnAudit',
        params: { id: row.id },
        query: { orderType: this.orderType }
      })
    },
    handleWithdrawPurchasePlan(row) {
      this.$confirm('确定要撤回这个订单退货吗？', '提示', { type: 'warning' }).then(() => {
        API_orderReturn.withdraworderReturn(row.id).then(() => {
          this.$message.success('撤回成功！')
          this.GET_orderReturnList()
        })
      }).catch(() => { })
    },
    handleSubmitPurchasePlan(row) {
      this.$confirm('确定要提交这个订单退货吗？', '提示', { type: 'warning' }).then(() => {
        API_orderReturn.submitorderReturn(row.id).then(() => {
          this.$message.success('提交成功！')
          this.GET_orderReturnList()
        })
      }).catch(() => { })
    },
    /** 删除订单退货 */
    handleDeletePurchasePlan() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定要删除这些订单退货吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_orderReturn.deleteorderReturn(ids).then(() => {
          this.$message.success('删除成功！')
          this.GET_orderReturnList()
        })
      }).catch(() => { })
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data
      }
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key])
      this.params.page_no = 1
      this.GET_orderReturnList()
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.purchasePlan_time_range) {
        this.params.start_time = parseInt(Number(this.advancedForm.purchasePlan_time_range[0]) / 1000)
        this.params.end_time = parseInt(Number(this.advancedForm.purchasePlan_time_range[1]) / 1000)
      }
      delete this.params.purchasePlan_time_range
      this.params.page_no = 1
      this.GET_orderReturnList()
    },

    /** 获取订单退货列表 */
    GET_orderReturnList() {
      this.loading = true
      this.params.order_type = this.orderType
      API_orderReturn.getorderReturnList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.print {
  margin-left: 790px;
}

.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    text-align: center;
  }
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
